<?php

namespace api\behaviors\actions;

use Yii;
use yii\web\NotFoundHttpException;

/**
 * 自定义详情搜索ViewAction，与\yii\rest\ViewAction类不同的是，本类可以按照多个条件进行搜索，并且只返回一条记录。
 * @package api\common\actions
 */
class ViewAction extends \yii\rest\ViewAction
{
    /**
     * 查找符合条件的model
     * @param string $condition 条件搜索数组类
     * @return mixed|\yii\db\ActiveRecordInterface
     */
    public function run($condition)
    {
        $model = $this->findModel($condition);
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }

        return $model;
    }


    /**
     * 重写父类方法，根据搜索条件获取一个model，去掉了按照主键搜索的逻辑
     *
     * @param string $condition
     * @return mixed
     * @throws NotFoundHttpException
     */
    public function findModel($condition)
    {
        if ($this->findModel !== null) {
            return call_user_func($this->findModel, $condition, $this);
        }

        /* @var $modelClass ActiveRecordInterface */
        $modelClass = $this->modelClass;

        $model = $modelClass::findOne($condition);

        if (isset($model)) {
            return $model;
        }

        throw new NotFoundHttpException("Object not found");
    }


    /**
     * 重写父类方法
     * @param array $params
     * @return mixed|null|\yii\db\ActiveRecordInterface
     */
    public function runWithParams($params)
    {
        $args = $params;
        Yii::debug('Running action: ' . get_class($this) . '::run(), invoked by ' . get_class($this->controller), __METHOD__);
        if (Yii::$app->requestedParams === null) {
            Yii::$app->requestedParams = $args;
        }

        if ($this->beforeRun()) {
            $result = $this->run($args);
            $this->afterRun();

            return $result;
        }

        return null;
    }

}